package com.my.xinyidaixi.Fragment;

import android.Manifest;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.my.xinyidaixi.Activity.ZongHe_WebView;
import com.my.xinyidaixi.Activity.daixi;
import com.my.xinyidaixi.Activity.feedback;
import com.my.xinyidaixi.Activity.jianxi;
import com.my.xinyidaixi.Adapter.RollViewAdapter;
import com.my.xinyidaixi.DataBase.Bean.Advlist;
import com.my.xinyidaixi.DataBase.Model.Over_UserModer;
import com.my.xinyidaixi.DataBase.Model.UserModel;
import com.my.xinyidaixi.Globe.MyApplication;
import com.my.xinyidaixi.Globe.MyUrl;
import com.my.xinyidaixi.HttpVolley.Volley_core;
import com.my.xinyidaixi.R;
import com.my.xinyidaixi.Util.CacheSave;
import com.my.xinyidaixi.Util.ToastUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wevey.selector.dialog.NormalAlertDialog;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zw on 2017/6/1.
 */
public class Home_Fragment extends Fragment {

    private RollPagerView mRollViewPager;
    private Context context= MyApplication.getInstance();
    private View fragment_1;
    private Intent intent;
    private LinearLayout jianxiButton,xixieButton,gxihuButton,service_introduction_button,service_area_button,price_center_button,feedback_button;
    private Bundle bundle;
    private ImageView middlebutton;
    private UserModel model=new Over_UserModer();
    private CacheSave cacheSave=new CacheSave();
    private ImageView middlebutton_2;
    private RefreshLayout refreshlayout;
    private String adv_url;
    private TextView fuwurexian;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private String num = "041166328728";
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden)
        {
            RollViewAdapter rollviewadapter=new RollViewAdapter();
            mRollViewPager.setAdapter(rollviewadapter);
            initimage();
        }
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragment_1 = inflater.inflate(R.layout.home,container,false);
        initdata();
        return fragment_1;
    }

    public void init_volley_date()
    {
        Volley_core volle=new Volley_core();
        volle.advlist(true);
        volle.Schoolinfo(true);
        volle.clothesinfo(true);
    }

    public void initdata()
    {

        fuwurexian = (TextView) fragment_1.findViewById(R.id.home_fuwurexian);
        fuwurexian.setOnClickListener(new Mylistener());

        refreshlayout = (RefreshLayout) fragment_1.findViewById(R.id.refreshLayout);
        refreshlayout.setOnRefreshListener(new OnRefreshListener() {
           // 设置刷新监听器
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                testHttp();
            }
        });
        //设置加载监听器
        refreshlayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(2000);
                ToastUtil.shortToast(context,"正在刷新");
            }
        });


        //图片滚动
        mRollViewPager = (RollPagerView) fragment_1.findViewById(R.id.home_roll_view_pager);
        mRollViewPager.setPlayDelay(5000);//设置播放时间间隔
        mRollViewPager.setAnimationDurtion(3000);//设置切换时间
        mRollViewPager.setHintView(new ColorPointHintView(context, Color.WHITE,Color.BLACK));//设置指示器颜色
        RollViewAdapter rollviewadapter=new RollViewAdapter();
        mRollViewPager.setAdapter(rollviewadapter);
        //图片滚动

        //中间Button
        jianxiButton = (LinearLayout) fragment_1.findViewById(R.id.jianxi);
        xixieButton = (LinearLayout) fragment_1.findViewById(R.id.xixie);
        gxihuButton = (LinearLayout) fragment_1.findViewById(R.id.gxihu);
        jianxiButton.setOnClickListener(new Mylistener());
        xixieButton.setOnClickListener(new Mylistener());
        gxihuButton.setOnClickListener(new Mylistener());

        middlebutton_2 = (ImageView) fragment_1.findViewById(R.id.middlebutton_2);
        middlebutton_2.setScaleType(ImageView.ScaleType.FIT_XY);
        middlebutton_2.setOnClickListener(new Mylistener());
        middlebutton = (ImageView) fragment_1.findViewById(R.id.middlebutton);
        middlebutton.setScaleType(ImageView.ScaleType.FIT_XY);
        middlebutton.setOnClickListener(new Mylistener());
        initimage();
        //下面Button
        service_introduction_button = (LinearLayout) fragment_1.findViewById(R.id.service_introduction);
        service_area_button = (LinearLayout) fragment_1.findViewById(R.id.service_area);
        price_center_button = (LinearLayout) fragment_1.findViewById(R.id.price_center);
        feedback_button = (LinearLayout) fragment_1.findViewById(R.id.feedback);
        service_introduction_button.setOnClickListener(new Mylistener());
        service_area_button.setOnClickListener(new Mylistener());
        price_center_button.setOnClickListener(new Mylistener());
        feedback_button.setOnClickListener(new Mylistener());
    }


    public void initimage()
    {
        String url_1="";
        String url_2="";
        ArrayList<Advlist> item=model.get_advlist();
        for(int i=0;i<item.size();i++)
        {
            if(item.get(i).getAdv_id().equals("4"))
            {
                url_1=item.get(i).getAdv_img_url(); //地址url回头再获取
                cacheSave.finalBitmap(middlebutton,url_1);
            }
            if(item.get(i).getAdv_id().equals("5"))
            {
                url_2=item.get(i).getAdv_img_url(); //地址url回头再获取
                adv_url=item.get(i).getAdv_url();
                cacheSave.finalBitmap(middlebutton_2,url_2);
            }
            if(url_1!=""&&url_2!="")
            {
                break;
            }
        }
       /* if(item!=null)
        {
            url_1=item.get(1).getAdv_img_url();
            url_2=item.get(2).getAdv_img_url();
            adv_url=item.get(2).getAdv_url();
        }*/


       /* finalBitmap = FinalBitmap.create(context);
        finalBitmap.configBitmapLoadThreadSize(4);//定义线程数量
        finalBitmap.configDiskCachePath(cacheSave.getCachePath()+ "/imageCache"); //设置缓存目录
        finalBitmap.configDiskCacheSize(1024 * 1024 * 10);//设置缓存大小
        finalBitmap.display(middlebutton,url_1);
        finalBitmap.display(middlebutton_2,url_2);*/

    }

    public  class  Mylistener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            switch (v.getId())
            {
                case R.id.jianxi:
                    intent=new Intent();
                    bundle=new Bundle();
                    intent.setClass(context,jianxi.class);
                    bundle.putInt("position",0);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;
                case R.id.xixie:
                    intent=new Intent();
                    bundle=new Bundle();
                    intent.setClass(context,jianxi.class);
                    bundle.putInt("position",1);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;
                case R.id.gxihu:
                    intent=new Intent();
                    bundle=new Bundle();
                    intent.setClass(context,jianxi.class);
                    bundle.putInt("position",2);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.service_introduction:
                    intent=new Intent();
                    intent.setClass(context,ZongHe_WebView.class);
                    intent.putExtra("url", MyUrl.service_introduction_url);
                    intent.putExtra("text","服务介绍");
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.service_area:
                    intent=new Intent();
                    intent.setClass(context,ZongHe_WebView.class);
                    intent.putExtra("url", MyUrl.service_area_url);
                    intent.putExtra("text","服务范围");
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.feedback:
                    intent=new Intent();
                    intent.setClass(context, feedback.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.price_center:
                    intent=new Intent();
                    intent.setClass(context,ZongHe_WebView.class);
                    intent.putExtra("url", MyUrl.jiamuzhongxin_url);
                    intent.putExtra("text","价目中心");
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    /*intent=new Intent();
                    intent.setClass(context, price_center.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);*/
                    break;
                case R.id.middlebutton:
                    intent=new Intent();
                    intent.setClass(context,daixi.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.middlebutton_2:
                   // ToastUtil.shortToast(context,"点击了第二栏");
                    intent=new Intent();
                    intent.setClass(context,ZongHe_WebView.class);
                    intent.putExtra("url",adv_url);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.ani_right_get_into,R.anim.ani_left_sign_out);
                    break;

                case R.id.home_fuwurexian:
                    fuwurexian_Dialog();
                    break;
            }
        }
    }

    //测试网站连接
    public void testHttp ()
    {
        String url=MyUrl.schoolinfo_url;
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e)
            {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run()
                    {
                        ToastUtil.shortToast(context,"网络请求失败");
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run()
                    {
                        model.delete_advlist();
                        model.delete_cloth_info();
                        model.delete_school_address();
                        init_volley_date();
                        refreshlayout.finishRefresh(2000);
                        ToastUtil.shortToast(context,"刷新完成");
                        cacheSave.clearfinalBitmap();
                    }
                });
            }
        });
    }

    private void fuwurexian_Dialog() {

        new NormalAlertDialog.Builder(getActivity()).setTitleVisible(false)
                .setContentText("服务热线：0411-66328728")
                .setContentTextColor(R.color.black)
                .setLeftButtonText("确定")
                .setLeftButtonTextColor(R.color.black)
                .setRightButtonText("不确定")
                .setRightButtonTextColor(R.color.black)
                .setOnclickListener(new com.wevey.selector.dialog.DialogInterface.OnLeftAndRightClickListener<NormalAlertDialog>() {
                    @Override
                    public void clickLeftButton(NormalAlertDialog dialog, View view) {

                       /*model.delete_order(id);*/

                        // 检查是否获得了权限（Android6.0运行时权限）
                        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                            // 没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CALL_PHONE)) {
                                // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                //  Toast.makeText(gengduo.this, "请授权！", Toast.LENGTH_LONG).show();

                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }else{
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
                            }
                        }else
                        {
                            // 已经获得授权，可以打电话
                            CallPhone();
                        }

                        dialog.dismiss();//对话框消失
                    }

                    @Override
                    public void clickRightButton(NormalAlertDialog dialog, View view) {

                        dialog.dismiss();
                    }
                })
                .build()
                .show();
    }
    private void CallPhone() {
        String number =num;

        // 拨号：激活系统的拨号组件
        Intent intent = new Intent(); // 意图对象：动作 + 数据
        intent.setAction(Intent.ACTION_DIAL); // 设置动作
        Uri data = Uri.parse("tel:" + number); // 设置数据
        intent.setData(data);
        startActivity(intent); // 激活Activity组件

    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    CallPhone();
                } else {
                    // 授权失败！
                    // Toast.makeText(this, "授权失败！", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }
}

